package freebase;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.util.*;

import sun.security.util.Debug;

public class FBMatchDetailToDir {

	public static HashMap<Integer,String> loadwpidname(String file)throws Exception{
		HashMap<Integer,String>map = new HashMap<Integer,String>();
		BufferedReader br = new BufferedReader(new InputStreamReader
				(new FileInputStream(file), "utf-8"));
		String line = "";
		while((line = br.readLine())!=null){
			String []abc = line.split("\t");
			int a = Integer.parseInt(abc[1]);
			String title = abc[2];
			map.put(a, title);
		}
		br.close();
		return map;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		
		BufferedReader br = new BufferedReader(new InputStreamReader
				(new FileInputStream(args[0]), "utf-8"));
		HashMap<Integer,String>map= loadwpidname(args[2]);
		String line = "";
		String lasttype = "";
		String []buffer=null;
		ArrayList<String[]> list = new ArrayList<String[]>();
		
		System.out.println("begin parsing file:");
		int ln = 0;
		while((line = br.readLine())!=null){
			String []abc = line.split("\t");
			String type = abc[3];
			if(lasttype.equals("") || type.equals(lasttype)){
				list.add(abc);
			}else{
				String filename = args[1]+"/"+lasttype.replace("/","@");
				OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename),"utf-8");
				for(String []a: list){
					int wpid = Integer.parseInt(a[1]);
					String title = map.get(wpid);
					osw.write(wpid+"\t"+title+"\t");
					for(int i=2;i<a.length;i++)osw.write(a[i]+"\t");
					osw.write("\n");
				}
				System.out.println("Dealing with \t"+lasttype);
				osw.close();
				list.clear();
				list.add(abc);
			}
			lasttype = type;
		}
		br.close();
	}

}
